package com.shoutao.website.controller.datacontroller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shoutao.website.contact.*;
import com.shoutao.website.entity.Productcomment;
import com.shoutao.website.entity.Productinfo;
import com.shoutao.website.entity.Productparameterinfo;
import com.shoutao.website.entity.Productpicinfo;
import com.shoutao.website.mapper.ProductcommentMapper;
import com.shoutao.website.mapper.ProductinfoMapper;
import com.shoutao.website.mapper.ProductparameterinfoMapper;
import com.shoutao.website.mapper.ProductpicinfoMapper;
import com.shoutao.website.utils.IpUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description:
 * @Param:
 * @return:
 * @Author: cqin
 * @Date: 2019/11/5
 */
@RestController
@RequestMapping(value = "/api/product")
public class ProductController {


    @Autowired
    private ProductinfoMapper productinfoMapper;
    @Autowired
    private ProductpicinfoMapper productpicinfoMapper;
    @Autowired
    private ProductcommentMapper productcommentMapper;
    @Autowired
    private ProductparameterinfoMapper productparameterinfoMapper;

    public static List<Productinfo> productinfoList = new ArrayList<>();
    public static Map<Integer, Productinfo> productInfoMap = new HashMap<>();

    public static Map<String, Integer> ipMap = new HashMap<>();


    @ApiOperation(value = "产品显示/查询接口", notes = "产品显示/查询接口")
    @RequestMapping(value = "/searchProduct.do", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "request", value = "请求", dataType = "SearchProductRequest", required = true)
    })
    public SearchProductResponse searchProduct(HttpServletRequest httpServletRequest, SearchProductRequest request) throws SQLException {

        String ip = IpUtil.getIpAddr(httpServletRequest);
        if(ipMap.containsKey(ip)){
            ipMap.put(ip, ipMap.get(ip)+1);
        }else{
            ipMap.put(ip, 1);
        }

        long time = System.currentTimeMillis();


        SearchProductResponse response = new SearchProductResponse();
        List<Productinfo> resultList = new ArrayList<>();
        if (CollectionUtils.isEmpty(productinfoList)) {
            productinfoList = productinfoMapper.selectList(null);
            initMap(productinfoList);
        }

        long time2 = System.currentTimeMillis();
        System.out.println("initMap cost"+(time2-time));

        if (StringUtils.isNotBlank(request.getTags())) {
            for (Productinfo productinfo : productinfoList) {
                if (productinfo.getProducttags().contains(request.getTags())) {
                    resultList.add(productinfo);
                }
            }
        }
        if (StringUtils.isNotBlank(request.getRelativeIds())) {
            productinfoList.forEach(x -> {
                if (Arrays.stream(request.getRelativeIds().split(";")).anyMatch(p -> p.equals(x.getId().toString())))
                    resultList.add(x);
            });
        }
        response.setProductinfoList(toFacadeList(resultList));

        long time3 = System.currentTimeMillis();
        System.out.println("toFacadeList cost"+(time3-time));

        return response;
    }

    /**
     *
     * @param productinfoList
     * @return
     */
    private List<ProductinfoFacade>  toFacadeList(List<Productinfo> productinfoList) {
        List<ProductinfoFacade> resultList = new ArrayList<>();
        for (Productinfo productinfo : productinfoList) {
            ProductinfoFacade facade = new ProductinfoFacade();
            BeanUtils.copyProperties(productinfo, facade);

            // Productpicinfo productpicinfo = fileMap.get(productinfo.getThumbnailspicurl());
            // if(productpicinfo != null){
            //    facade.setPic(productpicinfo.getPicdata());
            // }

            resultList.add(facade);
        }
        return resultList;

    }

    private void initMap(List<Productinfo> productinfoList ) {

        for (Productinfo productinfo : productinfoList) {
            productInfoMap.put(productinfo.getId(), productinfo);
        }
    }


    @ApiOperation(value = "产品提交接口", notes = "产品提交接口")
    @RequestMapping(value = "/showIps.do", method = RequestMethod.GET)
    public String showIps(HttpServletRequest httpServletRequest) throws SQLException {

        EditProductResponse response = new EditProductResponse();

        HttpSession httpSession = httpServletRequest.getSession();
        if (httpSession == null || httpSession.getAttribute("user") == null
                || !"admin".equals((String) httpSession.getAttribute("user"))) {
            response.setResult(false);
            response.setResultMessage("没有足够的权限");
            return "没有足够的权限";
        }

        return ipMap.toString();
    }


    @ApiOperation(value = "产品提交接口", notes = "产品提交接口")
    @RequestMapping(value = "/saveProduct.do", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "request", value = "请求", dataType = "EditProductRequest", required = true)
    })
    public EditProductResponse saveProduct(HttpServletRequest httpServletRequest, EditProductRequest request) throws SQLException {


        EditProductResponse response = new EditProductResponse();

        HttpSession httpSession = httpServletRequest.getSession();
        if (httpSession == null || httpSession.getAttribute("user") == null
                || !"admin".equals((String) httpSession.getAttribute("user"))) {
            response.setResult(false);
            response.setResultMessage("没有足够的权限");
            return response;
        }

        if(StringUtils.isEmpty(request.getProductattribute())){
            response.setResult(false);
            response.setResultMessage("产品属性不能为空");
            return response;
        }

        if(StringUtils.isEmpty(request.getProducttags())){
            response.setResult(false);
            response.setResultMessage("产品标签不能为空");
            return response;
        }


        if (request.getProductId() != 0) {
            Productinfo productinfo = productinfoMapper.selectById(request.getProductId());
            if (productinfo == null) {
                response.setResult(false);
                return response;
            }

            mapProductinfo(productinfo, request);
            productinfoMapper.updateById(productinfo);

            response.setResult(true);
            response.setResultMessage("更新成功");
        } else {

            Productinfo productinfo = new Productinfo();
            mapProductinfo(productinfo, request);
            productinfoMapper.insert(productinfo);

            // 需要往productpic里插入数据
            /*Productpicinfo productpicinfo = new Productpicinfo();
            productpicinfo.setProductid(productinfo.getId());
            productpicinfo.setPicurl(request.getDetailPicurl());
            productpicinfoMapper.insert(productpicinfo);*/

            response.setResult(true);
            response.setResultMessage("新增成功");
        }

        // 更新缓存内容
        productinfoList = productinfoMapper.selectList(null);
        initMap(productinfoList);
        return response;

    }

    private void mapProductinfo(Productinfo productinfo, EditProductRequest request) {
        productinfo.setProductname(request.getProductname());
        productinfo.setProductdesc(request.getProductdesc());
        productinfo.setProducttags(request.getProducttags());
        productinfo.setProducttype(0);
        productinfo.setThumbnailspicurl(request.getThumbnailsPicurl());
        productinfo.setModelno(request.getModelno());
        productinfo.setStandard(request.getStandard());
        productinfo.setGuage(request.getGuage());
        productinfo.setColor(request.getColor());
        productinfo.setAvailablesize(request.getAvailableSize());
        productinfo.setProductstar(request.getProductstar());
        productinfo.setProductattribute(request.getProductattribute());
        productinfo.setRelativeid(request.getRelativeId());
    }


    @ApiOperation(value = "产品详情接口", notes = "产品详情接口")
    @RequestMapping(value = "/showProductDetail.do", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "request", value = "请求", dataType = "SearchProductRequest", required = true)
    })
    public ShowProductDetailResponse showProductDetail(HttpServletRequest httpServletRequest, ShowProductDetailRequest request) throws SQLException {

        ShowProductDetailResponse response = new ShowProductDetailResponse();

        // 基础信息
        long start = System.currentTimeMillis();

        Productinfo productinfo = productInfoMap.get(request.getProdcutId());
        long end1 = System.currentTimeMillis();
        System.out.println("productInfoMap.get cost:"+(end1-start));
        response.setProductinfo(productinfo);

        if(ImageController.fileMap.containsKey(productinfo.getThumbnailspicurl())){
            response.setPic(ImageController.fileMap.get(productinfo.getThumbnailspicurl()).getPicdata());
        }

        long end2 = System.currentTimeMillis();
        System.out.println("ImageController cost:"+(end2-end1));


        // 图片
        Productpicinfo productpicinfoSample = new Productpicinfo();
        productpicinfoSample.setProductid(request.getProdcutId());
        List<Productpicinfo> productpicinfoList = productpicinfoMapper.selectList(new QueryWrapper<>(productpicinfoSample));
        response.setProductpicinfoList(productpicinfoList);

        long end3 = System.currentTimeMillis();
        System.out.println("Productpicinfo cost:"+(end3-end2));



        // 评论
        Productcomment productcommentSample = new Productcomment();
        productcommentSample.setProductid(request.getProdcutId());
        List<Productcomment> productcommentList = productcommentMapper.selectList(new QueryWrapper<>(productcommentSample));
        response.setProductcommentList(productcommentList);

        long end4 = System.currentTimeMillis();
        System.out.println("Productcomment cost:"+(end4-end3));

        // 参数
        Productparameterinfo productparameterinfoSample = new Productparameterinfo();
        productparameterinfoSample.setProductid(request.getProdcutId());
        List<Productparameterinfo> productparameterinfoList = productparameterinfoMapper.selectList(new QueryWrapper<>(productparameterinfoSample));
        response.setProductparameterinfoList(productparameterinfoList);

        long end5 = System.currentTimeMillis();
        System.out.println("Productparameterinfo cost:"+(end5-end4));

        return response;
    }


    @ApiOperation(value = "提交产品图片", notes = "提交产品图片")
    @RequestMapping(value = "/saveProductImg.do", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "request", value = "请求", dataType = "ImageUploadRequest", required = true)
    })
    public ImageUploadResponse saveProductImg(HttpServletRequest httpServletRequest) throws SQLException, IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) httpServletRequest;
        MultipartFile file = multipartRequest.getFile("file");

        // 得到文件名称
        String realFileName = file.getOriginalFilename();
        String suffix = realFileName.substring(realFileName.indexOf("."),
                realFileName.length());

        //得到 文件名
        String filename = getUUID32() + suffix;
        BASE64Encoder base64Encoder =new BASE64Encoder();//base64
        //将该字符串保存到数据库即可
        String baseimg = "data:" + file.getContentType()+";base64," + base64Encoder.encode(file.getBytes());

        Productpicinfo productpicinfo = new Productpicinfo();
        productpicinfo.setProductid(0);
        productpicinfo.setPicurl("");
        productpicinfo.setPicname(filename);
        productpicinfo.setPicdata(baseimg);

        productpicinfoMapper.insert(productpicinfo);


        ImageUploadResponse response = new ImageUploadResponse();
        response.setFileName(filename);
        return response;
    }




    @ApiOperation(value = "刷新缓存", notes = "刷新缓存")
    @RequestMapping(value = "/reloadCache.do", method = RequestMethod.POST)
    @ApiImplicitParams({
    })
    public ReloadCacheResponse reloadCache(HttpServletRequest httpServletRequest) throws SQLException, IOException {

        productinfoList = productinfoMapper.selectList(null);
        initMap(productinfoList);

        ReloadCacheResponse reloadCacheResponse = new ReloadCacheResponse();
        reloadCacheResponse.setResult(true);
        return reloadCacheResponse;
    }


    /**
     *
     * @return
     */
    public String getUUID32() {
        return UUID.randomUUID().toString().replace("-", "").toLowerCase();
    }


}
